<?php
class SF_Orderrepayment_RepaymentController extends Mage_Core_Controller_Front_Action 
{
	protected function isLoggedIn()
	{
		
		if(!Mage::getSingleton('customer/session')->isLoggedIn())
		{
			 $this->_redirect('customer/account/login');
			 return false;
			
		}
		return true;;
	}
	protected  function is_closerepay(Mage_Sales_Model_Order $order) {
	   if(Mage::helper("orderrepayment")->repayorder($order)){
	       return false;
	   }else{
	       return true;
	   }
	}
	public function repayAction()
	{
	   if($this->isLoggedIn()&&$this->_loadValidOrder()){
	       $this->loadLayout();
	       $this->renderLayout();
	   }else{
	       $this->_redirect('customer/account');
	   }
	    
	}
	/**
	 * Check order view availability
	 *
	 * @param   Mage_Sales_Model_Order $order
	 * @return  bool
	 */
	protected function _canViewOrder($order)
	{
	    $customerId = Mage::getSingleton('customer/session')->getCustomerId();
	    $availableStates = Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates();
	    if ($order->getId() && $order->getCustomerId() && ($order->getCustomerId() == $customerId)
	        && in_array($order->getState(), $availableStates, $strict = true)
	        ) {
	            return true;
	        }
	        return false;
	}
	/**
	 * Try to load valid order by order_id and register it
	 *
	 * @param int $orderId
	 * @return bool
	 */
	protected function _loadValidOrder($orderId = null)
	{
	    if (null === $orderId) {
	        $orderId = (int) $this->getRequest()->getParam('order_id');
	    }
	    if (!$orderId) {
	    
	        $this->_forward('noRoute');
	        return false;
	    }
	  
	    $order = Mage::getModel('sales/order')->load($orderId);
	    if($this->is_closerepay($order)){
	        $this->_redirect('customer/account');
	    }
	    if ($this->_canViewOrder($order)) {
	        Mage::register('current_order', $order);
	        return true;
	    } else {
	        $this->_redirect('*/*/history');
	    }
	    return false;
	}
	
	protected function changePaymentMethod($method, $orderId)
	{
		$this->isLoggedIn();
		if($method == null || $orderId == null)
		{
			Mage::getSingleton('core/session')->addError($this->__('access violation!'));
			$this->_redirect('orderrepayment/repayment/index');
		}
		
		$order   		 = Mage::getModel('sales/order')->load($orderId);
		$orderCustomId   = $order->getCustomerId();
		$currentCustomId = Mage::getSingleton('customer/session')->getId();
		if($orderCustomId != $currentCustomId)
		{
			Mage::getSingleton('core/session')->addError($this->__('Order No. is wrong!'));
			$this->_redirect('orderrepayment/repayment/index');
		}

		$payment = $order->getPayment();
		$payment->setMethod($method); // Assuming 'test' is updated payment method
		$payment->save();
		$order->save();
		return $order->getIncrementId();
		
	}

	public function redirectAction()
	{
		Mage::log($_SESSION['core'],1,'rumall.log');
	    $pament_info = $this->getRequest()->getPost();
		$this->isLoggedIn();
		$method  = $pament_info['method'];
		$orderId = $pament_info['orderid'];
		$IncrementId = $this->changePaymentMethod($method, $orderId); // change the payment method
		switch ($method)
		{
			case 'creditcard_payment':
				/*开启了钱海支付，就用钱海。否则就用钱宝*/
				if(Mage::getStoreConfig('payment/oceanpayment_creditcard/active')){
					$redirectUrl = 'opcreditcard/payment/redirect/';
				}else{
					$redirectUrl = 'creditcard/payment/redirect';
				}
				break;
			case 'yandex_payment':
				/*开启了钱海支付，就用钱海。否则就用钱宝*/
				if(Mage::getStoreConfig('payment/oceanpayment_yandex/active')){
					$redirectUrl = 'opyandex/payment/redirect/';
				}else{
					$redirectUrl = 'yandex/payment/redirect/';
				}
				break;
			case 'qiwi_payment':
				/*开启了钱海支付，就用钱海。否则就用钱宝*/
				if(Mage::getStoreConfig('payment/oceanpayment_qiwi/active')){
					$_SESSION['opqiwi_pay_countryCode'] = $pament_info['qiwiCountryCode'];
					$_SESSION['opqiwi_pay_userName'] = $pament_info['qiwiUsername'];
					$redirectUrl = 'opqiwi/payment/redirect/';
				}else{
					$_SESSION['qiwiCountryCode'] = $pament_info['qiwiCountryCode'];
					$_SESSION['qiwiUsername'] = $pament_info['qiwiUsername'];
					$redirectUrl = 'qiwi/payment/redirect/';
				}
				break;
		}
		Mage::getSingleton("core/session")->setData("isrepayment", true);
		Mage::getSingleton("core/session")->setData('repay_IncrementId',$IncrementId);
		$this->_redirectUrl(Mage::getBaseUrl().$redirectUrl);
	}

    public function ifarmeRedirectAction(){
            $param= $this->getRequest()->getParam('status');
            $ulr =Mage::getBaseUrl()."orderrepayment/repayment/".$param;
            $html = '<html><body>';
            $html.= '<script type="text/javascript">top.location.href = "' . $ulr. '";</script>';
            $html.= '</body></html>';
            echo $html;
    }
	public function successAction()
	{
		$this->isLoggedIn();
		$this->loadLayout();
		$this->getLayout()->getBlock('root')->setTemplate('page/1column.phtml');
		$this->getLayout()->getBlock('content')->append($this->getLayout()->createBlock('orderrepayment/success'));
		$this->renderLayout();
	}

	public function waitAction()
	{
		$this->isLoggedIn();
		$this->loadLayout();
		$this->getLayout()->getBlock('root')->setTemplate('page/1column.phtml');
		$this->getLayout()->getBlock('content')->append($this->getLayout()->createBlock('orderrepayment/wait'));
		$this->renderLayout();
	}

	public function failureAction()
	{
		$this->isLoggedIn();
		$this->loadLayout();
		$this->getLayout()->getBlock('root')->setTemplate('page/1column.phtml');
		$this->getLayout()->getBlock('content')->append($this->getLayout()->createBlock('orderrepayment/failure'));
		$this->renderLayout();
	}
}
